// src/main/java/com/bookmanager/dao/FavoriteDAO.java
package com.bookmanager.dao;

import com.bookmanager.model.Favorite;
import com.bookmanager.util.DatabaseUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class FavoriteDAO {

    // 添加收藏
    public boolean addFavorite(String userId, int bookId) {
        // 先检查是否已经收藏
        if (isBookFavorite(userId, bookId)) {
            System.out.println("⚠️ 用户 " + userId + " 已经收藏过图书 " + bookId);
            return false; // 已经收藏过，返回false
        }

        String sql = "INSERT INTO favorites (user_id, book_id) VALUES (?, ?)";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, userId);
            stmt.setInt(2, bookId);

            boolean success = stmt.executeUpdate() > 0;
            if (success) {
                System.out.println("✅ 收藏成功: userId=" + userId + ", bookId=" + bookId);
            }
            return success;
        } catch (SQLException e) {
            e.printStackTrace();
            // 处理重复收藏的情况
            if (e.getMessage().contains("Duplicate entry")) {
                System.out.println("❌ 已经收藏过这本书: userId=" + userId + ", bookId=" + bookId);
            }
        }
        return false;
    }

    // 取消收藏
    public boolean removeFavorite(String userId, int bookId) {
        String sql = "DELETE FROM favorites WHERE user_id = ? AND book_id = ?";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, userId);
            stmt.setInt(2, bookId);

            return stmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    // 获取用户的所有收藏
    public List<Favorite> getUserFavorites(String userId) {
        System.out.println("🔍 FavoriteDAO - 开始查询用户收藏: userId=" + userId);

        List<Favorite> favorites = new ArrayList<>();
        String sql = "SELECT f.*, b.title as book_title, b.author as book_author " +
                "FROM favorites f " +
                "JOIN books b ON f.book_id = b.book_id " +
                "WHERE f.user_id = ? " +
                "ORDER BY f.create_time DESC";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, userId);
            ResultSet rs = stmt.executeQuery();

            int count = 0;
            while (rs.next()) {
                count++;
                Favorite favorite = extractFavoriteFromResultSet(rs);
                favorites.add(favorite);
                System.out.println("✅ FavoriteDAO - 找到收藏: " + favorite.getBookTitle() + " (ID: " + favorite.getBookId() + ")");
            }
            System.out.println("📊 FavoriteDAO - 总共找到 " + count + " 个收藏");

        } catch (SQLException e) {
            System.out.println("❌ FavoriteDAO - 查询收藏失败: " + e.getMessage());
            e.printStackTrace();
        }
        return favorites;
    }

    // 检查是否已经收藏
    public boolean isBookFavorite(String userId, int bookId) {
        String sql = "SELECT COUNT(*) FROM favorites WHERE user_id = ? AND book_id = ?";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, userId);
            stmt.setInt(2, bookId);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                return rs.getInt(1) > 0;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    private Favorite extractFavoriteFromResultSet(ResultSet rs) throws SQLException {
        Favorite favorite = new Favorite();
        favorite.setFavoriteId(rs.getInt("favorite_id"));
        favorite.setUserId(rs.getString("user_id"));
        favorite.setBookId(rs.getInt("book_id"));

        Timestamp createTime = rs.getTimestamp("create_time");
        if (createTime != null) {
            favorite.setCreateTime(createTime.toLocalDateTime());
        }

        favorite.setBookTitle(rs.getString("book_title"));
        favorite.setBookAuthor(rs.getString("book_author"));

        return favorite;
    }
}